package com.itheima.web.controller.system;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.system.SysLog;
import com.itheima.web.controller.BaseServlet;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

@WebServlet("/system/sysLog")
public class SysLogServlet extends BaseServlet {

    public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer pageNum = 1;
        Integer pageSize = 5;
        String visitTime = "";

        try {
            pageNum = Integer.valueOf(request.getParameter("pageNum"));
            pageSize = Integer.valueOf(request.getParameter("pageSize"));
            visitTime = request.getParameter("visitTime");
        } catch (Exception e) {

        }
        PageHelper.startPage(pageNum, pageSize);
        List<SysLog> sysLogList = sysLogService.findAll(visitTime);
        PageInfo<SysLog> page = new PageInfo<>(sysLogList);
        //将数据保存到指定的位置
        request.setAttribute("page", page);
        request.setAttribute("searchMap", visitTime);
        //跳转页面
        request.getRequestDispatcher("/pages/system/syslog/syslog-list.jsp").forward(request, response);
    }

    public void deleteSel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String ids = request.getParameter("ids");
        System.out.println(ids);
        //执行业务
        sysLogService.deleteSel(ids);
        //请求转发
        this.list(request, response);
    }

    public void downloadLog(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //返回的数据类型为文件xlsx类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = new String("系统日志文件.xlsx".getBytes(), "iso8859-1");
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);

        //生成报告的文件，然后传递到前端页面
        ByteArrayOutputStream os = sysLogService.getLog();
        //获取产生响应的流对象
        ServletOutputStream sos = response.getOutputStream();
        //将数据从原始的字节流对象中提取出来写入到servlet对应的输出流中
        os.writeTo(sos);
        //将输出流刷新
        sos.flush();
        os.close();
    }
}
